package com.scalar.chiptrack.operations.shippingRequest.actionCommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.operations.shippingRequest.forms.ShippingRequestForm;
import com.scalar.chiptrack.operations.shippingRequest.ShippingRequest;
import com.scalar.chiptrack.operations.shippingRequest.dao.ShippingRequestDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * Created by ChandraSekahr.
 * User: Administrator
 * Date: Nov 21, 2005
 * Time: 2:30:09 PM
 */
public class ShippingRequestCancelCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/shippingRequest.do";
    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws ScalarException
    {
        ShippingRequestForm shippingRequestForm   = ( ShippingRequestForm ) form;
        ShippingRequest shippingRequest           = shippingRequestForm.getShippingRequest();
        HttpSession mSession              = request.getSession();
        User user                         = ( User )mSession.getAttribute( SessionKeys.USER_KEY );
        HashMap errors                    = new HashMap();
        HashMap info                      = new HashMap();
        String isCancel                   = request.getParameter( "isCancel" );
        String forward                    = "search";
        int shippingRequestId             = -1;

        if ( user == null )
        {
            mSession.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.APPROVE_SORT_RELEASE , User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }
        try
        {
        	try{
                shippingRequestId = Integer.parseInt( ( request.getParameter( "shipReqId" ) ).trim() );
            }catch( NumberFormatException nfe )
            {
                shippingRequestId = -1;
            }

            if("true".equalsIgnoreCase( isCancel ) )
            {
                if ( !isTokenValid ( request ) )
                {
                    errors.put ( "Ship Request Already Cancelled", null );
                    request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                    shippingRequestForm.setShippingRequest( new ShippingRequest() );

                    request.setAttribute( "vendorList", ShippingRequestDAO.loadClassStroeLocations( null )  );
                    request.setAttribute( "partNumberList", ShippingRequestDAO.getProductList( Constants.LOCATION_TYPE_CLASS_STORE ) );
                    request.setAttribute( "yearList", ShippingRequestDAO.getYearList() );
                    request.setAttribute( "statusList", ShippingRequestDAO.getStatusList() );
                    saveToken ( request );
                    //forwarding to the search page
                    return ( mapping.findForward ( "search" ) );
                }

                resetToken ( request );

                shippingRequest.setShipRequestId( shippingRequestId ) ;
                shippingRequest.setStatus( ShippingRequest.STAUS_CANCELLED );
                // to laod the ship request lot object
                ShippingRequestDAO.loadShippingRequestLotDetails( null, shippingRequest );
                boolean isLotShipped = ShippingRequestDAO.checkWhetherAnyLotIsShipped( null, shippingRequest );
                if( isLotShipped )
                {
                    errors.put( "Ship Request Cannot be Cancelled, Some Lot(s) Already Shipped", null );
                }
                else
                {
                     // to cancel the Ship req
                    ShippingRequestDAO.cancelShippingRequest( null, shippingRequest );

                    ShippingRequestDAO.updateShipRequestStatus( null, shippingRequest,  user.getUserId() );
                    info.put( "Ship Request has been Cancelled", null );
                    info.put ( "View/Print ,Click here to <a href='javascript:printView("+shippingRequest.getShipRequestId() +");' onmouseover=\"window.status='Click here to View/print Ship Request';return true\" onmouseout=\"window.status='';return true\"> view/print </a>Ship Request Details", null );
                }

                shippingRequestForm.setShippingRequest( new ShippingRequest() );
                request.setAttribute( "vendorList", ShippingRequestDAO.loadClassStroeLocations( null )  );
                request.setAttribute( "partNumberList", ShippingRequestDAO.getProductList( Constants.LOCATION_TYPE_CLASS_STORE ) );
                request.setAttribute( "yearList", ShippingRequestDAO.getYearList() );
                request.setAttribute( "statusList", ShippingRequestDAO.getStatusList() );
            }
            else
            {
                //TO LOAD THE SAVED SHIPPING REQUEST INFO
                shippingRequest  = ShippingRequestDAO.getShippingRequest( null, shippingRequestId );

                shippingRequestForm.setShippingRequest( shippingRequest );
                request.setAttribute( "isCancel", "true" );
                saveToken( request );
                forward = "printView";
            }
        }
        catch ( Exception e )
        {
            // Writes this error information onto the screen
            Logger.error( "Error while processing the request for cancelling ship request", e );
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "Error while processing the request for cancelling ship request" );
            e.printStackTrace();

            // Prints more information in the pop-up
            mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( "Error while processing the request for cancelling ship request", e ) );
        }

        request.setAttribute( INFO_MESSAGES, info );
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );

        return mapping.findForward( forward );
    }

}